<?php

namespace common\components\request;

use yii\web\BadRequestHttpException;

/**
 * Created by PhpStorm.
 * User: yang lei
 * Date: 2018/4/27
 * Time: 下午5:38
 */
class Request extends \yii\web\Request
{

    protected $currentRawBody;

    /**
     * @param $key
     *
     * @return mixed
     * @throws BadRequestHttpException
     */
    public function body($key = null)
    {
        if ($this->currentRawBody === null) {
            $this->currentRawBody = json_decode($this->getRawBody(), true);
        }
        if ($key === null) {
            return $this->currentRawBody;
        }
        $argc = explode('.', $key);
        $temp = $this->currentRawBody;
        foreach ($argc as $item) {
            if (!isset($temp[$item])) {
                throw  new BadRequestHttpException("缺少参数$item");
            }
            $temp = $temp[$item];
        }

        return $temp;
    }

    /**
     * 获取对象模式的rawBody数据
     *
     * @param null $key
     * @param null $message
     *
     * @return mixed
     * @throws \yii\web\BadRequestHttpException
     */
    public function getRawBodyAsObject($key = null, $message = null)
    {
        if ($this->currentRawBody === null) {
            $this->currentRawBody = json_decode($this->getRawBody());
        }
        $result = $this->currentRawBody;

        if ($key === null) {
            return $result;
        }

        $argc = explode('.', $key);
        foreach ($argc as $item) {
            if (!is_object($result) || !isset($result->$item)) {
                $message = is_null($message) ? sprintf('缺少参数:[%s]', $item) : $message;
                throw  new BadRequestHttpException($message);
            }

            $result = $result->$item;
        }

        return $result;
    }
}
